package udp

import (
	"fmt"
	"iot-base/common/tunnel/protocol"
	"net"
	"strconv"
)

type Rcver interface {
	OnData(data []byte, pHeader *protocol.Header, nlen int, conn *net.UDPConn, addr *net.UDPAddr)
	Seq() uint32
	Port() int
}

type UDPBase struct {
	//Recvers []Rcver
	recverMap map[uint32]Rcver
	port      int
	conn      *net.UDPConn
}

func Begin(port int, rcver Rcver) {
	pUDP := &UDPBase{
		port:      port,
		recverMap: make(map[uint32]Rcver),
	}
	pUDP.recverMap[rcver.Seq()] = rcver

	udpAddr, _ := net.ResolveUDPAddr("udp4", ":"+strconv.Itoa(port))

	//监听端口
	udpConn, err := net.ListenUDP("udp", udpAddr)
	pUDP.conn = udpConn
	if err != nil {
		fmt.Println(err)
	}
	defer udpConn.Close()
	buffer := make([]byte, 1024)
	for {
		len, udpAddr, err := udpConn.ReadFromUDP(buffer)
		if err == nil {

			pHeader, _ := protocol.GetHeader(buffer, len)
			if pHeader != nil {
				recv := pUDP.recverMap[pHeader.Seq]
				if recv == nil {
					recv = pUDP.recverMap[0]
				}
				if recv != nil {
					fmt.Println("get data-----", buffer[0:len])
					recv.OnData(buffer, pHeader, len, udpConn, udpAddr)
				}
			}
		}

	}

}
